package com.louis.iread.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.louis.iread.R;
import com.louis.iread.bean.Book;
import com.louis.iread.bean.BookMgr;
import com.louis.iread.bean.ContentItem;
import com.louis.iread.bean.NovelPageItem;
import com.louis.iread.bean.SearchResultItem;
import com.louis.iread.bean.Website;
import com.louis.iread.bean.WebsiteMgr;
import com.louis.iread.event.EventType;
import com.louis.iread.event.ReadEvent;
import com.louis.iread.net.HttpUtil;
import com.louis.iread.skin.SkinMgr;
import com.louis.iread.utils.ConstValue;
import com.louis.iread.utils.DateUtil;
import com.louis.iread.utils.NovelUtil;
import com.louis.iread.utils.SimpleTask;
import com.louis.iread.utils.ThreadPool;
import com.yarolegovich.lovelydialog.LovelyDialogCompat;
import com.yarolegovich.lovelydialog.LovelyProgressDialog;
import com.yarolegovich.lovelydialog.LovelyStandardDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.xutils.ex.DbException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;

@ContentView(R.layout.activity_novel_info)
public class NovelInfoActivity extends SwipeBackActivity {

    private SwipeBackLayout mSwipeBackLayout;
    Book mBook;
    Website mSite;        //小说所在站点
    List<ContentItem> mContents = new ArrayList<>();   //章节目录列表
    String mMainUrl;    //小说主页url
    String mContentsUrl;    //小说目录url
    String mAuthor; //作者
    String mType; //小说类型
    String mState; //小说写作状态
    String mUpdateTime; //更新时间
    String mNovelName; //小说名
    String mDesc;    //小说摘要
    String mCoverUrl; //小说封面url
    String mLatestArticle; //最新章节
    int mTotalArticleNum = 0;

    boolean mIsReading = false;

    @ViewInject(R.id.coverView)
    private ImageView mCoverView;

    @ViewInject(R.id.novel_name)
    private TextView mNovelNameView;

    @ViewInject(R.id.novel_author)
    private TextView mNovelAuthorView;

    @ViewInject(R.id.novel_state)
    private TextView mNovelStateView;

    @ViewInject(R.id.novel_type)
    private TextView mNovelTypeView;

    @ViewInject(R.id.novel_update_time)
    private TextView mUpdateTimeView;

    @ViewInject(R.id.desc)
    private TextView mDescView;

    @ViewInject(R.id.novel_site)
    private TextView mSiteView;

    @ViewInject(R.id.latest)
    private TextView mLatestView;

    @ViewInject(R.id.total_num)
    private TextView mTotalNumView;

    @ViewInject(R.id.addBookShelftView)
    private AppCompatButton mAddRemoveView;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SkinMgr.getInstance().unregister(this);
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SkinMgr.getInstance().register(this);
        EventBus.getDefault().register(this);
        x.view().inject(this);
        //实现沉浸式状态栏
        if (Build.VERSION.SDK_INT >= 19) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        ImageView back = (ImageView) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        //设置右划关闭页面
        mSwipeBackLayout = getSwipeBackLayout();
        mSwipeBackLayout.setEdgeTrackingEnabled(SwipeBackLayout.EDGE_ALL);
        Intent intent = getIntent();

        SearchResultItem searchItem = (SearchResultItem)intent.getSerializableExtra(ConstValue.SEARCH_ITEM);
        if (searchItem != null) {
            mBook = BookMgr.getMgr().getBook(searchItem.getNovelUrl());
        }
        NovelPageItem pageItem = (NovelPageItem) intent.getSerializableExtra(ConstValue.CLASS_PAGE_ITEM);
        if (pageItem != null) {
            mBook = BookMgr.getMgr().getBook(pageItem.getNovelUrl());
        }
        long bookId = intent.getLongExtra(ConstValue.BOOK_INDEX, -1);
        if (bookId >= 0) {
            mBook = BookMgr.getMgr().getBook(bookId);
        }
        if (mBook != null) {
            mMainUrl = mBook.getMainUrl();
            mContentsUrl = mBook.getContentsUrl();
            mCoverUrl = mBook.getCoverUrl();
            mSite = WebsiteMgr.getManager().getWebsite(mBook.getSite());
            mAuthor = mBook.getAuthor();
            mType = mBook.getType();
            mUpdateTime = mBook.getUpdateTime();
            mNovelName = mBook.getNovelName();
            mDesc = mBook.getDesc();
            mState = mBook.getState();
            mLatestArticle = mBook.getLatestArticle();
            mNovelStateView.setText(String.format(getResources().getString(R.string.write_state), mState));
            mUpdateTimeView.setText(String.format(getResources().getString(R.string.update_time), mUpdateTime));
            mDescView.setText(mDesc);
            mLatestView.setText(String.format(getResources().getString(R.string.latest_article), mLatestArticle));
            int totalNum = 0;
            try {
                totalNum = mBook.getArticles().size();
            } catch (DbException e) {
                e.printStackTrace();
            }
            mTotalNumView.setText(String.format(getResources().getString(R.string.total_article_num), totalNum));
        } else {
            if (searchItem != null) {
                mMainUrl = searchItem.getNovelUrl();
                mContentsUrl = searchItem.getContentsUrl();
                mCoverUrl = searchItem.getCover();
                mSite = searchItem.getWebsite();
                mAuthor = searchItem.getNovelAuthor();
                mType = searchItem.getNovelType();
                mUpdateTime = searchItem.getNovelUpdateTime();
                mNovelName = searchItem.getNovelTitle();
                mLatestArticle = searchItem.getNovelLatestArticle();
                mUpdateTime = searchItem.getNovelUpdateTime();
            } else if (pageItem != null) {
                mMainUrl = pageItem.getNovelUrl();
                mContentsUrl = pageItem.getContentsUrl();
                mCoverUrl = pageItem.getCover();
                mSite = WebsiteMgr.getManager().getMainSite();
                mAuthor = pageItem.getAuthor();
                mType = pageItem.getType();
                mUpdateTime = pageItem.getUpdateTime();
                mNovelName = pageItem.getNovelName();
            }
            getNovelInfo();
        }

        mIsReading = intent.getBooleanExtra(ConstValue.IS_READING, false);

        //设置封面
        if (mCoverUrl != null && !"".equals(mCoverUrl.trim())) {
            Glide.with(mCoverView.getContext())
                    .load(mCoverUrl)
                    .apply(new RequestOptions().placeholder(R.drawable.nocover).error(R.drawable.nocover))
                    .into(mCoverView);
        }
        //设置小说名
        mNovelNameView.setText(mNovelName);
        //设置小说作者
        mNovelAuthorView.setText(String.format(getResources().getString(R.string.novel_author), mAuthor));
        mNovelStateView.setText("写作状态: 未知");
        //设置小说类型
        mNovelTypeView.setText(String.format(getResources().getString(R.string.novel_type), mType));
        //设置小说来源
        if (mSite != null) {
            mSiteView.setText(String.format(getResources().getString(R.string.site_name), mSite.getSiteName()));
        }
        if (mUpdateTime != null && mUpdateTime.length() > 0) {
            mUpdateTimeView.setText(String.format(getResources().getString(R.string.update_time), mUpdateTime));
        }

        if (mLatestArticle != null && mLatestArticle.length() > 0) {
            mLatestView.setText(String.format(getResources().getString(R.string.latest_article), mLatestArticle));
        }

        if (mBook != null) {
            mAddRemoveView.setText(R.string.remove_from_booksheft);
        } else {
            mAddRemoveView.setText(R.string.add_booksheft);
        }
        mAddRemoveView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mBook == null) {
                    addBook();
                } else {
                    //阅读状态的小说不能删除
                    if (mIsReading) {
                        Toast.makeText(view.getContext(), R.string.dont_rm_book, Toast.LENGTH_SHORT).show();
                        return;
                    }

                    new LovelyStandardDialog(NovelInfoActivity.this)
                            .setTopColorRes(R.color.darkGreen)
                            .setButtonsColorRes(R.color.darkDeepOrange)
                            .setIcon(R.drawable.ic_star_border_white_36dp)
                            .setTitle(R.string.delete_ask)
                            .setMessage(mBook.getNovelName())
                            .setPositiveButton(android.R.string.ok, LovelyDialogCompat.wrap(new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    removeBookByMainUrl(mMainUrl);
                                    mAddRemoveView.setText(R.string.add_booksheft);
                                }
                            }))
                            .setNegativeButton(android.R.string.no, null)
                            .show();
                }

            }
        });

        AppCompatButton readNowView = (AppCompatButton) findViewById(R.id.readNowView);
        readNowView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mBook == null) {
                    boolean bRet = addBook();
                    if (!bRet) {
                        Toast.makeText(view.getContext(), R.string.data_exception, Toast.LENGTH_SHORT).show();
                        return;
                    }
                } else {

                }
                if (mIsReading) {
                    finish();
                    return;
                }
                Intent intent = new Intent(view.getContext(), ReadActivity.class);
                intent.putExtra(ConstValue.BOOK_INDEX, mBook.getId());
                view.getContext().startActivity(intent);
            }
        });

        AppCompatButton downloadView = (AppCompatButton) findViewById(R.id.downBookView);
        downloadView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mBook == null) {
                    boolean bRet = addBook();
                    if (!bRet) {
                        Toast.makeText(view.getContext(), R.string.data_exception, Toast.LENGTH_SHORT).show();
                        return;
                    }
                }

                Toast.makeText(view.getContext(), R.string.download_remainder_bg, Toast.LENGTH_SHORT).show();
                ThreadPool.getInstance().commit(new Runnable() {
                    @Override
                    public void run() {
                        mBook.downloadRemainderArticleContent();
                    }
                });
            }
        });
    }

    private LovelyProgressDialog mDialog;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsgEvent(ReadEvent event) {
        switch (event.getEventType()) {
            case LOAD_PAGE_SUCCESS:
                parseNovelInfo((Document) event.getObj());
                mTotalNumView.setText(String.format(getResources().getString(R.string.total_article_num), mTotalArticleNum));
                if (mDialog != null) {
                    mDialog.dismiss();
                }
                break;
            case LOAD_PAGE_FAILED:
                if (mDialog != null) {
                    mDialog.dismiss();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 从html解析出小说信息
     * @param document
     */
    public void parseNovelInfo(Document document) {
        if (mSite.getState() != null && !mSite.getState().trim().equals("")) {
            Elements state = document.select(mSite.getState());
            for (Element element : state) {
                mState = element.text().replace("写作", "").replace("状态", "").replace("进度", "").replace(":", "").replace("：", "").trim();
                mNovelStateView.setText(String.format(getResources().getString(R.string.write_state), mState));
                break;
            }
        }

        if (mUpdateTime == null || mUpdateTime.length() == 0) {
            Elements updateTime = document.select(mSite.getUpdateTime());
            for (Element element:updateTime) {
                mUpdateTime = element.text().replace("更新时间", "").replace("：", "").trim();
                mUpdateTimeView.setText(String.format(getResources().getString(R.string.update_time), mUpdateTime));
                break;
            }
        }

        if (mLatestArticle == null || mLatestArticle.length() == 0) {
            if (mSite.getLatestArticle() != null && !mSite.getLatestArticle().trim().equals("")) {
                Elements latestArticle = document.select(mSite.getLatestArticle());
                for (Element element : latestArticle) {
                    mLatestArticle = element.text().replace("最新章节", "").replace("：", "").replace(":", "").trim();
                    mLatestView.setText(String.format(getResources().getString(R.string.latest_article), mLatestArticle));
                    break;
                }
            }
        }

        if (mSite.getNovelDesc() != null && !mSite.getNovelDesc().trim().equals("")) {
            Elements desc = document.select(mSite.getNovelDesc());
            for (Element element : desc) {
                mDesc = element.text();
                mDescView.setText(mDesc);
                break;
            }
        }
    }

    /**
     * 从html解析出小说目录
     * @param document
     */
    public void parseNovelContents(Document document) {
        Elements contentsList = document.select(mSite.getContents());
        for (Element item : contentsList) {
            ContentItem contentItem = new ContentItem();
            contentItem.setWebsite(mSite);
            contentItem.setContentTitle(item.text());
            contentItem.setUrl(item.absUrl("href"));
            mContents.add(contentItem);
//            Log.i(contentItem.getContentTitle(), contentItem.getUrl());
        }
        mTotalArticleNum = mContents.size();
    }

    private void showProgressDialog() {
        mDialog = new LovelyProgressDialog(this);
        mDialog.setIcon(R.drawable.ic_cast_connected_white_36dp)
                .setTitle(R.string.obtain_data)
                .setCancelable(true);
        mDialog.show();
    }

    /**
     * 获取小说元数据
     */
    public void getNovelInfo() {
        showProgressDialog();
        ThreadPool.getInstance().commit(new Runnable() {
            @Override
            public void run() {
                try {
                    String contents = HttpUtil.getStringFromUrl(mContentsUrl, mSite.getUserAgent(), mSite.getHost(), null);
                    if (contents == null) {
                        EventBus.getDefault().post(new ReadEvent(EventType.LOAD_PAGE_FAILED));
                        return;
                    }
                    Document document = Jsoup.parse(contents, mContentsUrl);
                    if (document == null){
                        EventBus.getDefault().post(new ReadEvent(EventType.LOAD_PAGE_FAILED));
                        return;
                    }
                    parseNovelContents(document);
                    Document doc = document;
                    if (!mContentsUrl.equals(mMainUrl)) {
                        String html = HttpUtil.getStringFromUrl(mMainUrl, mSite.getUserAgent(), mSite.getHost(), null);
                        if (html == null) {
                            EventBus.getDefault().post(new ReadEvent(EventType.LOAD_PAGE_FAILED));
                            return;
                        }
                        doc = Jsoup.parse(html, mMainUrl);
                    }
                    EventBus.getDefault().post(new ReadEvent(EventType.LOAD_PAGE_SUCCESS, doc));

                } catch (Exception e) {
                    e.printStackTrace();
                    EventBus.getDefault().post(new ReadEvent(EventType.LOAD_PAGE_FAILED));
                }
            }
        });
    }

    /*
    添加小说到书架
     */
    public boolean addBook() {
        SimpleDateFormat dataFomat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = dataFomat.format(new Date());
        mBook = new Book();
        mBook.setNovelName(mNovelName);
        mBook.setAuthor(mAuthor);
        mBook.setRead(false);
        mBook.setType(mType);
        mBook.setSite(mSite.getHost());
        mBook.setDesc(mDesc);
        mBook.setMainUrl(mMainUrl);
        mBook.setCoverUrl(mCoverUrl);
        mBook.setContentsUrl(mContentsUrl);
        mBook.setReadingArticleWordNum(0);
        mBook.setReadingArticleIndex(0);
        mBook.setAddTime(DateUtil.getSqliteDateTime(null));
        mBook.setReadTime(currentTime);
        mBook.setUpdateTime(currentTime);
        mBook.setState(mState);
        if (mContents == null || mContents.size() == 0) {
            Toast.makeText(getApplicationContext(), R.string.add_failed, Toast.LENGTH_SHORT).show();
            return false;
        }

        boolean bRet = BookMgr.getMgr().addBook(mBook);
        if (!bRet) {
            Toast.makeText(getApplicationContext(), R.string.add_failed, Toast.LENGTH_SHORT).show();
            return false;
        }

        bRet = BookMgr.getMgr().addArticles(mBook.getId(), mContents);
        if (!bRet) {
            Toast.makeText(getApplicationContext(), R.string.add_contents_failed, Toast.LENGTH_SHORT).show();
            return false;
        }
        mAddRemoveView.setText(R.string.remove_from_booksheft);
        EventBus.getDefault().post(new ReadEvent(EventType.ADD_BOOK));
        return true;
    }

    /*
    根据main url把小说从书架移除
     */
    public void removeBookByMainUrl(String mainUrl) {
        if (mainUrl == null || mainUrl.length() == 0) {
            return;
        }
        new SimpleTask(this, true){
            @Override
            public void doOnPreExe() {

            }

            @Override
            public void doOnPublish(Object ojb) {

            }

            @Override
            public Integer doOnBackgroundExe() {
                BookMgr.getMgr().removeBook(mBook.getId());
                mBook = null;
                EventBus.getDefault().post(new ReadEvent(EventType.REMOVE_BOOK));
                return 1;
            }

            @Override
            public void doOnComplete(Integer result) {
            }
        }.execute();
    }
}
